//
//  WBNetworkManager+Extension.swift
//  微博
//
//  Created by Mstarc on 2016/12/1.
//  Copyright © 2016年 Mstarc. All rights reserved.
//

import Foundation

//封装新浪微博的网络请求
extension WBNetworkManager{

    /// 微博字典数组
    ///
    /// - parameter complete: 完成回调[list:微博字典数组,是否成功]
    
    
    
    /// 微博字典数组
    ///
    /// - parameter since_id: since_id 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    /// - parameter max_id:   max_id 返回ID小于或等于max_id的微博，默认为0
    /// - parameter complete: 完成回调[list:微博字典数组,是否成功]
    func statusList(since_id:Int64 = 0,max_id:Int64 = 0, complete:@escaping (_ list:[[String:AnyObject?]], _ isSuccess:Bool)->())  {
    
        /// 用 网络工具 加载 微博数据
        // parameter complete:
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let max_id = max_id > 0 ? max_id-1 : 0
        let parameter = ["since_id":since_id,"max_id":max_id]
        print(parameter)
        tokenRequest(URLString: urlStr, parameters: parameter ) { (json, isSuccess) in
            
            //从list中获取 statuses字典数组
            //如果 as? 失败 ,result = nil
            let list = json as? [String:AnyObject]
            let result = list?["statuses"]
            print("---数据-----\(result)")
            complete(result as! [[String : AnyObject]], isSuccess)
            
            
            
        }
    }
    
    /// 返回微博未读数量
    func unreadCount(complete:@escaping (_ count:Int)->())  {
        
        guard let uid = userAccount.uid else {
            return
        }
        let urlStr = "https://rm.api.weibo.com/2/remind/unread_count.json"
    
        let params = ["uid":uid]
        tokenRequest(URLString: urlStr, parameters: params) { (json, isSuccess) in
            
            let dict = json as? [String:AnyObject]
            let count = dict?["status"] as? Int
            complete(count ?? 0)
            print(json)
        }
        
    }
  
}

// MARK: - OAuth相关方法
extension WBNetworkManager{
    //加载 accessToken
    func loadAccessToken(code:String)  {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":WBAppKey,
                      "client_secret":WBAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WBRedirectURI]
        //发起网络请求
        request(method: .POST, URLString: urlString, parameters: params) { (json, isSuccess) in
            print(json)
        }
    }
}

